<?php
namespace app\common\components;

use yii\web\Controller;
use Yii;
use yii\web\HttpException;

/**
 * Class BaseWebController 基础get post 操作封装&cookie 封装&json 返回值封装
 * Author: yanhaoqiang
 * @package app\common\components
 */
class BaseWebController extends Controller {
    public $enableCsrfValidation = false;

    /**
     * [post post 参数值]
     * @param $key
     * @param string $default
     * @return array|mixed
     */
    public function post($key, $default = "") {
        return \Yii::$app->request->post($key, $default);
    }

    /**
     * [get get参数值]
     * @param $key
     * @param string $default
     * @return array|mixed
     */
    public function get($key, $default = "") {
        return \Yii::$app->request->get($key, $default);
    }

    /**
     * [setCookie 设置cookie]
     * @param $name
     * @param $value
     * @param int $expire
     * @return void
     */
    protected function setCookie($name, $value, $expire = 0) {
        $cookies = \Yii::$app->response->cookies;
        $cookies->add(new \yii\web\Cookie([
            'name' => $name,
            'value' => $value,
            'expire' => $expire
        ]));
    }

    /**
     * [getCookie 获取cookie]
     * @param $name
     * @param string $default_val
     * @return mixed
     */
    protected function getCookie($name, $default_val = '') {
        $cookies = \Yii::$app->request->cookies;
        return $cookies->getValue($name, $default_val);
    }

    /**
     * [removeCookie 移除cookie]
     * @param $name
     * @return void
     */
    protected function removeCookie($name) {
        $cookies = \Yii::$app->response->cookies;
        $cookies->remove($name);
    }

    /**
     * [renderJSON 渲染json]
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return void
     */
    protected function renderJSON($data = [], $msg = "ok", $code = 200) {
        header('Content-type: application/json');
        echo json_encode([
            "code" => $code,
            "msg" => $msg,
            "data" => $data,
            "req_id" => uniqid()
        ]);

        return \Yii::$app->end();
    }

    /**
     * [renderJS 统一js提醒]
     * @param $msg
     * @param string $url
     * @return string
     */
    protected function renderJS($msg, $url = "/") {
        return $this->renderPartial("@app/views/common/js", ['msg' => $msg, 'location' => $url]);
    }
}


